package core.android.tools;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.telephony.SmsMessage;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import rx.functions.Action1;

/**
 * @作者: XQ
 * @创建时间：16/5/23 下午10:05
 * @类说明: 监听短信工具
 */
public class AKSMSUtil {
    public static Action1<String> smscallback;
    static SMSBroadcastReceiver smsBroadcastReceiver;//监听短信
    static SMSObserver smsObserver;

    public static void regestierSMSObserver() {
        Uri uri = Uri.parse("content://sms");
        //注册短信的监听
        smsObserver = new SMSObserver();
        AKActivityUtil.INSTANCE.getApplication().getContentResolver().registerContentObserver(uri, true, smsObserver);
    }

    public static void regestierSMSBroadcast() {
        //生成广播处理
        smsBroadcastReceiver = new SMSBroadcastReceiver();
        //实例化过滤器并设置要过滤的广播
        IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
        //注册广播
        AKActivityUtil.INSTANCE.getApplication().registerReceiver(smsBroadcastReceiver, intentFilter);
    }

    public static void ondestory() {
        //解除注册短信的监听
        if (smsObserver != null) {
            AKActivityUtil.INSTANCE.getApplication().getContentResolver().unregisterContentObserver(smsObserver);
        }
        if (smsBroadcastReceiver != null) {
            AKActivityUtil.INSTANCE.getApplication().unregisterReceiver(smsBroadcastReceiver);
        }
    }

    /**
     * 从字符串中截取连续6位数字组合 ([0-9]{" + 6 + "})截取六位数字 进行前后断言不能出现数字 用于从短信中获取动态密码
     *
     * @param str 短信内容
     * @return 截取得到的6位动态密码
     */
    public static String getDynamicPassword(String str) {
        // 6是验证码的位数一般为六位
        Pattern continuousNumberPattern = Pattern.compile("(?<![0-9])([0-9]{" + 6 + "})(?![0-9])");
        Matcher m = continuousNumberPattern.matcher(str);
        String dynamicPassword = "";
        while (m.find()) {
            dynamicPassword = m.group();
        }
        return dynamicPassword;
    }

    /**
     * 尝试读取短信
     */
    public static void attempReadSMS() {
        Uri inboxUri = Uri.parse("content://sms/inbox");
        Cursor c = AKActivityUtil.INSTANCE.getApplication().getContentResolver().query(inboxUri, null, null, null, "date desc");
        if (c != null) {
            if (c.moveToFirst()) {
                AK.d("读短信成功");
            } else {
                AK.d("读短信失败");
            }
            c.close();
        }
    }


    public static class SMSObserver extends ContentObserver {

        public SMSObserver() {
            super(new Handler());
        }

        @Override
        public void onChange(boolean selfChange, Uri uri) {
            super.onChange(selfChange, uri);
            AK.d("main", "SMS has changed!");
            AK.d("main", uri.toString());
            // 短信内容变化时，第一次调用该方法时短信内容并没有写入到数据库中,return
            if (uri.toString().equals("content://sms/raw")) {
                return;
            }
            Uri inboxUri = Uri.parse("content://sms/inbox");
            Cursor c = AKActivityUtil.INSTANCE.getApplication().getContentResolver().query(inboxUri, null, null, null, "date desc");
            if (c != null) {
                if (c.moveToFirst()) {
                    String sender = c.getString(c.getColumnIndex("address"));
                    String body = c.getString(c.getColumnIndex("body"));
                    String code = getDynamicPassword(body);
                    AK.d("短信验证码:" + code);
                    if (code != null && smscallback != null) {
                        smscallback.call(code);
                    }
                } else {
                    AK.e("用户拒绝读短信");
                }
                c.close();
            }

        }

    }


    public static class SMSBroadcastReceiver extends BroadcastReceiver {

        public SMSBroadcastReceiver() {
            super();
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            Object[] pdus = (Object[]) intent.getExtras().get("pdus");
            for (Object pdu : pdus) {
                SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu);
                String sender = smsMessage.getDisplayOriginatingAddress();
                String content = smsMessage.getMessageBody();

                AK.d("短信内容:" + content);
                String code = AKSMSUtil.getDynamicPassword(content);
                AK.d("短信验证码:" + code);
                if (code != null && smscallback != null) {
                    smscallback.call(code);
                    smscallback = null;
                }
            }
        }
    }
}
